package xyz.pyming.utils.http;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

/**
 * 分片下载器
 */
public class UnitDownloader implements Runnable {


    //开始为止
    private int from;
    //结束位置
    private int to;
    //文件位置
    private File target;
    //下载地址
    private String uri;
    //分片id
    private int id;
    private CountDownLatch latch;

    public UnitDownloader(int from, int to, File target, String uri, int id, CountDownLatch latch) {
        this.from = from;
        this.to = to;
        this.target = target;
        this.uri = uri;
        this.id = id;
        this.latch = latch;
    }

    public int getFrom() {
        return from;
    }

    public int getTo() {
        return to;
    }

    @Override
    public void run() {
        //download and save data
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection();

            connection.setConnectTimeout(300 * 1000);

            connection.setReadTimeout(300 * 1000);
            System.out.println("分片:" + id + "开始下载，起始：" + from + ",结束" + to);
            connection.setRequestProperty("Range", "bytes=" + from + "-" + to);
            connection.connect();
            int totalSize = connection.getContentLength();
            InputStream inputStream = connection.getInputStream();
            RandomAccessFile randomAccessFile = new RandomAccessFile(target, "rw");
            randomAccessFile.seek(from);
            byte[] buffer = new byte[1024 * 1024];
            int readCount = inputStream.read(buffer, 0, buffer.length);
            while (readCount > 0) {
                totalSize -= readCount;
                randomAccessFile.write(buffer, 0, readCount);
                readCount = inputStream.read(buffer, 0, buffer.length);
            }
            System.out.println("分片：" + this.id + "完成");
            inputStream.close();
            randomAccessFile.close();
            connection.disconnect();
        } catch (IOException e) {
            ThreadDownloadManager.flag = "0";
            e.printStackTrace();
        } finally {
            //计数值减一
            latch.countDown();
        }
    }

}
